import React, { Component } from 'react';
import ThePagination from "@/components/ThePagination";
import { Form, Input, Select, Space, Button, DatePicker,Tooltip,Icon } from "antd";
import { SearchOutlined,QuestionCircleOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import { apiStockOutLibraryPage, apiStockOutLibraryDel, apiTSysDictionariesList, apiPrintStockOutLibrary } from '@/request/storageManager/outPut.js'
import TheQueryForm from '../../../components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import store from "@/store/store"
import _ from 'lodash';
import { getDateTime3 } from '@/utils/getDate'
import { exportSheetTable } from '@/utils/exportTable.js';

class OutPut extends Component {
    constructor() {
        super()
        this.formRef_search = React.createRef()
        this.queryFormRef = React.createRef()

        this.state = {
            columns: [
                {
                    title: "序号",
                    dataIndex: "index",
                    key: "index",
                    render:(text,record,index) =>{
                        return((this.state.pageData.pageNo - 1)*(this.state.pageData.pageSize) + (index + 1));
                    }
                },
                {
                    title: "出库单号",
                    dataIndex: "code",
                    key: "code",

                },
                {
                    title: "对应单号",
                    dataIndex: "otherCode",
                    key: "otherCode",
                    filterDropdown: true, // 自定义的列筛选功能，我们占位为信息提示Icon的位置
                    filterIcon: () => {
                        return (
                            <Tooltip zIndex={999} placement="top" title={()=>{
                                return <div>
                                    商城销售出库单：商城订单号<br />
                                    门店销售出库单：门店订单号<br />
                                    收银台出库单：门店订单号<br />
                                    调拨出库单(已完成)：入库单号
                                </div>
                            }
                            }  >
                                <QuestionCircleOutlined />
                            </Tooltip>
                        );
                    },
                },
                {
                    title: "出库日期",
                    dataIndex: "finishTime",
                    key: "finishTime",

                },
                {
                    title: "出库类型",
                    dataIndex: "dataTypeName",
                    key: "dataTypeName",
                },
                {
                    title: "出库仓库",
                    dataIndex: "libraryName",
                    key: "libraryName",

                },
                {
                    title: "状态",
                    dataIndex: "status",
                    key: "status",
                    render: (text) => {
                        if (text == 0) {
                            return <div style={{color:"red"}} >未完成</div>
                        } else {
                            return '已完成'
                        }
                    }

                },
                {
                    title: "登记人",
                    dataIndex: "createUserName",
                    key: "createUserName",

                },
                {
                    title: "登记日期",
                    dataIndex: "createTime",
                    key: "createTime",
                    defaultChange:true
                }, {
                    title: "操作",
                    dataIndex: "serviceShowFile",
                    key: "serviceShowFile",
                    fixed:'right',
                    render: (text, render) => {
                        return <div>
                            <TheButton haspermi={['storage:outPut:view']} onClick={() => this.view(render.id, render.dataType)}>查看详情</TheButton>
                            {
                                render.status == 0 && ![0, 1, 4, 5].includes(render.dataType) ?
                                    <TheButton haspermi={['storage:outPut:del']} onClick={() => this.del(render)}>删除</TheButton>
                                    :
                                    null
                            }

                        </div>
                    }
                },
            ],
            dataSource: [],
            pageData: {
                pageNo: 1,
                pageSize: 10

            },
            total: 0,
            code: '',
            newColumns: [],
            form_show: true,
            searchOption: [
                { field: 'code', label: '出库单号', placeholder: '请输入出库单号', required: false, rules: [], type: 'Input', defaultValue: '' },
                // { field: 'libraryName', label: '出库仓库', placeholder: '请选择出库仓库', required: false, rules: [], type: 'Input', options: [], defaultValue: '' },
                { field: 'otherCode', label: '对应单号', placeholder: '请输入对应单号', required: false, rules: [], type: 'Input', defaultValue: '' },
                { field: 'dataType', label: '出库类型', placeholder: '请选择出库类型', required: false, rules: [], type: 'Select', options: [], txt: 'name', value: 'value', api: apiTSysDictionariesList,params: { pid: '1603275910736543746' }, defaultValue: '' },
                { field: 'status', label: '状态', placeholder: '请选择状态', required: false, rules: [], type: 'Select', options: [{ label: '未完成', value: '0', }, { label: '已完成', value: '1' }], defaultValue: '' },
                // { field: 'createUserName', label: '登记人', placeholder: '请输入登记人', required: false, rules: [], type: 'Input', defaultValue: '' },
                { field: 'times', label: '出库日期', placeholder: '', required: false, rules: [], type: 'RangePicker', defaultValue: '' },
            ],
            queryForm: {},
            filterTitleKey: '',
        }
    }
    componentDidMount() {
        this.onColumnsFilter(this.state.columns)
        let searchParams = store.getState().searchValue
        let { pageNo, pageSize, queryForm, pathName } = searchParams
        if (searchParams && pageNo && pathName == 'outPut') {
            this.setState({
                queryForm,
                pageData: {
                    pageNo: pageNo, pageSize: pageSize
                }
            }, () => {
                this.queryFormRef.onSetDefault({
                    ...queryForm
                })
                this.getData()
            })
        } else {
            this.getData()
        }
    }
    view(id, type) {

        this.props.history.push('/allot/outPut/add/' + id + '/' + type + '/1603275910736543746')
    }
    getData(values) {
        let { pageNo, pageSize } = this.state.pageData
        if (values && !_.isEmpty(values.times)) {
            values.createStartTime = getDateTime3(values.times[0])
            values.createEndTime = getDateTime3(values.times[1])
            delete(values.times)
        }
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values }
        }, async () => {
            const params = {
                pageNo, pageSize, queryForm: this.state.queryForm
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName: 'outPut',
                    ...params
                }
            })
            let res = await apiStockOutLibraryPage({
                pageNo, pageSize, ...this.state.queryForm,
                firstTypeId:"1603275910736543746"
            })
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    total: res.totalCount
                })
            }
        })



    }
    del(row) {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "确定是否删除？",
            onOk: async () => {
                let res = await apiStockOutLibraryDel({ id: row.id })
                if (res.code === 0) {
                    this.pageChange(1, 10)
                    React.$message({
                        type: 'success',
                        content: res.codeMessage
                    })
                } else {
                    React.$message({
                        type: 'warning',
                        content: res.codeMessage
                    })
                }
            }
        });
    }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getData()
        })
    };
    onReset() {
        this.setState({
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }
    onFinishSearch() {
        let values = this.formRef_search.current.getFieldsValue()
        this.setState({
            code: values.code
        }, () => {
            this.pageChange(1, 10)
        })
    }
    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })
    }
    onFormSearch(values){
        this.setState({
            pageData:{pageNo:1,pageSize:10}
        },()=>{
            this.getData(values)
        })
    }

    toExport = async () => {
        const { queryForm } = this.state
        await apiPrintStockOutLibrary({ ...queryForm ,firstTypeId:"1603275910736543746", ids:'' }).then(res => {
            if (res.code === 0 && res.data) {
                let th_arr = [
                    {
                        title: '调拨出库单',
                        prop: '',
                        children: [
                            {
                                title: '序号',
                                prop: 'index'
                            },
                            {
                                title: '出库单号',
                                prop: 'code'
                            },
                            {
                                title: '对应单号',
                                prop: 'otherCode'
                            },
                            {
                                title: '出库类型',
                                prop: 'dataType'
                            },
                            {
                                title: '出库仓库',
                                prop: 'libraryName'
                            },
                            {
                                title: '对应入库仓库',
                                prop: 'inLibraryName'
                            },
                            {
                                title: '状态',
                                prop: 'status'
                            },
                            {
                                title: '物料名称',
                                prop: 'materialName',
                            },
                            {
                                title: "物料ID",
                                prop: "materialId",
                            },
                            {
                                title: '出库前库存',
                                prop: 'beforeCount',
                                valueType: 'number'
                            },
                            {
                                title: '出库数量',
                                prop: 'count',
                                valueType: 'number'

                            },
                            {
                                title: '操作时间',
                                prop: 'createTime',
                            },
                            {
                                title: '操作人',
                                prop: 'createUserName',
                            }
                        ]
                    },
                ]
                let tb_arr = []
                res.data.forEach((item, index) => {
                    let dataType = ""
                    switch (item.dataType) {
                        case 0:
                            dataType = "商城销售出库单"
                            break;
                        case 1:
                            dataType = "门店销售出库单"
                            break;
                        case 2:
                            dataType = "调拨出库单"
                            break;
                        case 3:
                            dataType = "手动创建出库单"
                            break;
                        case 4:
                            dataType = "发起砍价"
                            break;
                        case 5:
                            dataType = "收银台出库单"
                            break;
                        default:
                            break;
                    }
                    item.stockOutLibraryDetailVos.forEach(item2 => {
                        tb_arr.push({
                            index: item.noteIndex,
                            code: item.code || '/',
                            otherCode: item.otherCode || '/',
                            dataType: dataType || '/',
                            libraryName: item.libraryName || '/',
                            inLibraryName: item.inLibraryName || '/',
                            status: item.status === "0" ? "未完成" : "已完成" || '/',
                            materialName: item2.materialName || '/',
                            materialId: item2.materialId || '/',
                            beforeCount: item2.beforeCount || '/',
                            count: item2.count || '/',
                            createTime: item.createTime || '/',
                            createUserName: item.createUserName || '/',
                        })
                    })
                })
                const mergeProp = [
                    'index',
                    'code',
                    'otherCode',
                    'dataType',
                    'libraryName',
                    'status',
                    'createTime',
                    'createUserName',
                ]
                exportSheetTable({ fileName: '调拨出库单', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: true, mergeProp })
            }
        })
    }

    render() {
        let { columns, dataSource, pageData, total, form_show, searchOption, newColumns,filterTitleKey } = this.state
        return (
            <div className="p-layout-box commodity-examine">
                {/* <Form layout={'inline'} ref={this.formRef_search} onFinish={() => this.onFinishSearch()} style={{ marginBottom: 12 }}>
                    <Form.Item name={"code"}>
                        <Input style={{ width: 140 }} suffix={<SearchOutlined />} placeholder={"出库单号"} />
                    </Form.Item>
                    <Form.Item>
                        <Space size="small" style={{ marginLeft: 10 }}>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                            <Button onClick={() => this.resetSearch()}>重置</Button>
                        </Space>
                    </Form.Item>
                </Form> */}
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                              onReset={() => this.onReset()}
                              onGetValues={(values) => this.onFormSearch(values)} >
                </TheQueryForm>
                <TheTableExtend
                    columns={columns}
                    onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                    onTableRefresh={() => this.getData()}
                    onColumnsFilter={(value) => this.onColumnsFilter(value)}
                >
                    <TheButton haspermi={['storage:outPut:add']} size="middle" onClick={() => this.props.history.push('/allot/outPut/add/null/3/1603275910736543746')} type="primary">新增</TheButton>
                    <TheButton size="middle" type='default' onClick={() => this.toExport()} >导出</TheButton>
                </TheTableExtend>
                {/* <div style={{ marginBottom: 12 }}>
                    <TheButton haspermi={['storage:outPut:add']} size="middle" onClick={() => this.props.history.push('/storageManager/outPut/add/null/2')} type="primary">新增</TheButton>
                </div> */}
                <TheTable
                    scroll={{ x: "max-content", y: '63vh' }}
                    columns={newColumns}
                    dataSource={dataSource}
                />
                <ThePagination
                    pageNo={pageData.pageNo}
                    pageSize={pageData.pageSize}
                    total={total}
                    pageChange={this.pageChange}
                />
            </div>
        );
    }
}
export default OutPut
